package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.ydd.common.BusinessException;
import com.itheima.ydd.common.R;
import com.itheima.ydd.entity.YddUser;
import com.itheima.ydd.service.IYddUserService;
import com.itheima.ydd.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
//@CrossOrigin  //启用CORS跨域支持
@RestController
@RequestMapping("/home/index")
public class HomeIndexController {

    @Autowired
    private IYddUserService iYddUserService;

    /**
     * 前台登录
     *
     * @param yddUser
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody YddUser yddUser) {
        log.info("获取用户输入数据" + yddUser.getMobile() + yddUser.getPassword());

        //接收前端发来的密码和手机号  将密码经md5处理
        String password = yddUser.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        String mobile = String.valueOf(yddUser.getMobile());

        //构造条件
        //select * from sys_user where phone = ? and password = ? ;
        LambdaQueryWrapper<YddUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq( YddUser::getMobile, mobile)
                .eq(YddUser::getPassword, password);
        //执行方法查询 ydd用户信息
        YddUser user = iYddUserService.getOne(queryWrapper);

        //判断数据是否存在
        if (user == null) {
            throw new BusinessException("账号或密码错误!");
        }

        //将结果返还给前端 将用户 id 和用户名存入 token
        Map<String,Object> tokenMap = new HashMap<>();
        String mobile1 = user.getMobile()
                .replace("[","")
                .replace("]", "")
                .replace("\"", "");
        tokenMap.put("userId", user.getId());
        tokenMap.put("roleId",mobile1);

        String token = JwtUtils.getToken(tokenMap);

        return R.success("token",token);
    }
}
